package com.game.bullet;

import java.util.LinkedList;

import com.game.character.Character;
import com.game.framwork.itf.Graphics;
import com.game.tiledmap.TiledMap;
import com.game_ltdd.Resrouce;

public class BulletManager {

	private static BulletManager manager = null;
	public LinkedList<Bullet> listBullet;
	private TiledMap tiledMap;
	public LinkedList<Bullet> listBulletOfPlayer;

	BulletManager() {
		listBullet = new LinkedList<Bullet>();
		listBulletOfPlayer = new LinkedList<Bullet>();
	}
	
	public static BulletManager getInstance() {
		if (manager == null) {
			manager = new BulletManager();
		}
		return manager;
	}
	
	public void attachMap(TiledMap map) {
        this.tiledMap = map;
    }

	private int isHasBullet(LinkedList<Bullet> listBullet) {
        int count = listBullet.size();
        if (count <= 0) {
        	return -1;
        }
        for (int i = 0; i < count; i++) {
            if (listBullet.get(i).isDeath) {
                return i;
            }
        }
        return -1;
    }
	
	public void createBullet(Character user) {
		int index = isHasBullet(listBullet);
		if (index == -1) {
			Bullet bullet;
			bullet = new Bullet();
			bullet.initInfo(user);
			bullet.attachTiledMap(tiledMap);
			listBullet.add(bullet);	
		} else {
			listBullet.get(index).initInfo(user);	
		}
		Resrouce.setbullet.play(1, 0);
	}
	
	public void createBulletOfPlayer(Character user) {
		int index = isHasBullet(listBulletOfPlayer);
		if (index == -1) {
			Bullet bullet;
			bullet = new Bullet();
			bullet.initInfo(user);
			bullet.attachTiledMap(tiledMap);
			listBulletOfPlayer.add(bullet);	
		} else {
			listBulletOfPlayer.get(index).initInfo(user);	
		}
		Resrouce.setbullet.play(1, 0);
	}
	
	public void update(float deltaTime) {
		int count = listBullet.size();
		for (int i = 0; i < count; i++) {
			listBullet.get(i).updateInternal(deltaTime);
		}
		count = listBulletOfPlayer.size();
		for (int i = 0; i < count; i++) {
			listBulletOfPlayer.get(i).updateInternal(deltaTime);
		}
	}

	public void paint(Graphics g) {
		int count = listBullet.size();
		for (int i = 0; i < count; i++) {
			if (listBullet.get(i).isVisible) {
				listBullet.get(i).paintInternal(g);
			}
		}
		count = listBulletOfPlayer.size();
		for (int i = 0; i < count; i++) {
			if (listBulletOfPlayer.get(i).isVisible) {
				listBulletOfPlayer.get(i).paintInternal(g);
			}
		}
	}

	public void clear() {
		listBullet.clear();
		listBulletOfPlayer.clear();
	}
}
